<template>
  <div class="shoppingAdress">
    <!-- 黑色导航栏 -->
    <!-- <navTop></navTop> -->
    <!-- 一级导航栏 -->
    <!-- <navTwo class="navTwo"></navTwo> -->
    <main>
      <!-- <div class="title">
        <h1>收获地址</h1>
      </div> -->
      <div class="AddressBox">
        <!-- 点击弹出的表单填写 -->
        <div
          class="addAddressMask"
          v-show="isShowAddAddress"
          @mousewheel.prevent
          @touchmove.prevent
        >
          <div class="addressContent">
            <div class="title">
              <h3>添加地址</h3>
              <i @click="openAddAddress" class="el-icon-close"></i>
            </div>

            <div class="contentInput">
              <div>
                <el-input v-model="user.name" placeholder="您的姓名"></el-input>
              </div>
              <div>
                <el-input v-model="user.phone" placeholder="手机号"></el-input>
              </div>
              <div class="block">
                <el-cascader
                  v-model="user.address"
                  :options="options"
                  placeholder="请选择地址"
                ></el-cascader>
              </div>
              <div>
                <el-input
                  v-model="user.addressDatial"
                  placeholder="详细地址"
                ></el-input>
              </div>
              <div class="dizhi">
                <label for="dizhi"
                  ><input
                    type="checkbox"
                    name=""
                    id="dizhi"
                    v-model="isChecked"
                  /><span>默认收货地址</span></label
                >
              </div>
              <p>
                有关我们如何使用您的个人信息，请参阅我们的<span>隐私政策</span>。
              </p>
              <div>
                <button @click="isSureAdd">保存</button>
              </div>
            </div>
          </div>
        </div>
        <!-- <div  class="addBox" v-for="(item) in addressList" :key="(item.id)">
               <p>收货人: <span>{{ item.name }}</span></p>
               <p>手机号码: <span>{{item.phone }}</span></p>
               <p>地址: <span>{{  item.area_name}}</span></p>
               <p>详情地址:  <span>{{ item.desc }}</span></p>
               <p>地区id:<span>{{ item.area }}</span></p>
               <div class="ModifyAddress">
                <p
                @click="defaultAddress(item.id)"
                v-show="item.default_set == 1 ? false : true"
              >
                设为默认地址
              </p>
               <p v-show="item.default_set == 1 ? true : false">默认地址</p>
               <p @click="UpdataAddress(item.id)">编辑</p>
              <p @click="delAddress(item.id)">删除</p>
            </div>
        </div> -->
        <div class="title">
          <div class="add" @click="AddAddress">
            <i class="el-icon-edit"></i>新增收货地址
          </div>
          <div class="addresslength">
            <p>
              <i class="el-icon-warning"></i>已保存{{
                addresslength
              }}条地址还能保存{{ maxaddresslength }}条地址
            </p>
          </div>
        </div>
        <table cellspacing="0" cellpadding="20" class="table" width="70%">
          <tr class="THheight">
            <th>收货人</th>
            <th>所在地区</th>
            <th>详细地址</th>
            <!-- <th>邮编</th> -->
            <th>电话/手机</th>
            <th>操作</th>
            <th></th>
          </tr>
          <tr v-for="item in addressList" :key="item.id" class="Trheight">
            <td>{{ item.name }}</td>
            <td>{{ item.area_name }}</td>
            <td>{{ item.desc }}</td>
            <!-- <td>{{ item.post_code }}</td> -->
            <td>{{ item.phone }}</td>
            <td>
              <span @click="UpdataAddress(item.id)" class="updata">修改</span>
              | <span @click="delAddress(item.id)" class="del">删除</span>
            </td>
            <td @click="defaultAddress(item.id)" class="moren">
              <p v-show="item.default_set == 1 ? false : true">设为默认</p>
              <p v-show="item.default_set == 1 ? true : false" class="default">
                默认地址
              </p>
            </td>
          </tr>
        </table>
      </div>
    </main>
    <!-- 底部 -->
    <!-- <bottomList></bottomList> -->
  </div>
</template>

<script>
// import navTop from "../components/navtop";
// import navTwo from "../components/navTwo";
// import bottomList from "../components/bottomList";
import {
  getAddress,
  addAddress,
  delAddress,
  updataAddress,
  DefaultAddress,
  getDefault,
  shopCarDel,
  setOrder,
  getAllCity,
} from "../../api/test";
export default {
  data() {
    return {
      addressList: [],
      isShowAddAddress: false,
      isChecked: false,
      //用户填写的信息
      user: {
        name: "",
        phone: "",
        address: "",
        addressDatial: "",
      },
      //地址的集合
      options: [],
      //用户的地址存放
      userAddress: [],
      //保存按钮是修改还是添加的根据
      isBtn: "",
      //保存修改的ID
      isID: "",
      //用户勾选的商品
      orderlist: JSON.parse(sessionStorage.getItem("order")),

      //用户的默认地址信息
      userDefName: "",
      userDefAddress: "",
      //地址长度
      addresslength: "",
      maxaddresslength: "",
    };
  },
  components: {
    // navTop,
    // navTwo,
    // bottomList,
  },
  async created() {
    let res = await getAddress({
      phone: "13242998652",
      password: "123456",
    });
    console.log(res);
    this.addressList = res.data.result;

    //获取用户的默认地址
    try {
      let def = await getDefault({});
      // console.log(def);
      this.userDefName = def.data.result.name;
      this.userDefAddress = def.data.result.area_name + def.data.result.desc;
      this.addressList.forEach((item, index) => {
        if (item.default_set == 1) {
          this.addressList.splice(index, 1);
          this.addressList.unshift(item);
          // console.log(item);
        } else {
          item.default_set = 0;
        }
      });
    } catch (error) {
      console.log(error);
    }
    // console.log(123);
    if (sessionStorage.getItem("AllCity")) {
      this.options = JSON.parse(sessionStorage.getItem("AllCity"));
    } else {
      getAllCity().then((res) => {
        res.data.result.forEach((item, index) => {
          this.options.push({
            value: item.label,
            label: item.label,
            children: [],
          });

          item.children.forEach((item2, index2) => {
            this.options[index].children.push({
              value: item2.label,
              label: item2.label,
              children: [],
            });
            if (item2.children) {
              item2.children.forEach((item3, index3) => {
                // console.log(item3.labely);
                this.options[index].children[index2].children.push({
                  value: item3.label,
                  label: item3.label,
                });
              });
            }
          });
        });
        sessionStorage.setItem("AllCity", JSON.stringify(this.options));
      });
    }
  },
  updated() {
    //地址长度
    this.addresslength = this.addressList.length;
    //限制地址长度
    this.maxaddresslength = 20 - this.addresslength;
  },
  methods: {
    //添加收获地址(打开表单填写地址)
    AddAddress() {
      if (this.addresslength >= 20) {
        this.$message({
          message: "已经达到最大保存量",
          type: "warning",
        });
      } else {
        this.isShowAddAddress = true;
        this.isBtn = "add";
        //清空选择
        this.user.name = "";
        this.user.phone = "";
        this.user.address = "";
        this.user.addressDatial = "";
        this.isChecked = false;
      }
    },
    //关闭弹出的表单
    openAddAddress() {
      this.isShowAddAddress = false;
    },
    //保存按钮添加地址/修改地址
    async isSureAdd() {
      //根据isBtn的状态来判断是添加还是修改
      if (this.isBtn == "add") {
        addAddress({
          name: this.user.name,
          phone: this.user.phone,
          area: 1,
          area_name: this.user.address.join(" "),
          desc: this.user.addressDatial,
          default_set: this.isChecked == true ? 1 : 0,
        })
          .then((res) => {
            console.log(res);
            this.addressList.forEach((item) => {
              if (item.default_set === "1") {
                item.default_set = 0;
              }
            });
            this.addressList.unshift(res.data.result);
            console.log(res.data.result);
            this.isShowAddAddress = false;
            this.$message({
              message: res.data.msg,
              type: "success",
              duration: 1000,
            });
          })
          .catch((err) => {
            this.$message.error({
              message: err.response.data.msg,
              duration: 1500,
            });
          });
      } else if (this.isBtn == "updata") {
        if (this.isChecked) {
          let res2 = await getDefault({});
          console.log(res2.data.result);

          await updataAddress(res2.data.result.id, {
            name: res2.data.result.name,
            phone: res2.data.result.phone,
            area: 1,
            area_name: res2.data.result.address,
            desc: res2.data.result.addressDatial,
            default_set: 0,
          });
        }
        await updataAddress(this.isID, {
          name: this.user.name,
          phone: this.user.phone,
          area: 1,
          area_name: this.user.address.join(" "),
          desc: this.user.addressDatial,
          default_set: this.isChecked == true ? 1 : 0,
        })
          .then(async (res) => {
            this.isShowAddAddress = false;
            this.$message({
              message: "修改成功",
              type: "success",
              duration: 1000,
            });
            let res2 = await getAddress({});
            this.addressList = res2.data.result;
            this.addressList.forEach((item, index) => {
              if (item.default_set == 1) {
                // item.splice(index, 1);
                this.addressList.splice(index, 1);
                this.addressList.unshift(item);
              } else {
                item.default_set = 0;
              }
            });
          })
          .catch((err) => {
            this.$message.error({
              message: "修改失败",
              duration: 1000,
            });
          });
      }
    },
    async UpdataAddress(id) {
      this.isID = id;
      this.isShowAddAddress = true;
      this.isBtn = "updata";
      await getAddress({}).then(async (res) => {
        let arr = await res.data.result.filter((item) => {
          return item.id == id;
        });
        console.log(arr[0].default_set);
        this.user.name = arr[0].name;
        this.user.phone = arr[0].phone;
        this.user.address = arr[0].area_name.split(" ");
        this.user.addressDatial = arr[0].desc;
        this.isChecked = arr[0].default_set == "1" ? true : false;
      });
    },
    //删除地址
    delAddress(id) {
      this.$confirm("此操作将删除地址, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await delAddress(id);
          this.$message({
            type: "success",
            message: res.data.msg,
          });
          let newRes = await getAddress({});
          this.addressList = newRes.data.result;
          window.location.reload();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改默认地址
    async defaultAddress(id) {
      this.$confirm("此操作将修改默认地址, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await DefaultAddress(id);
          this.addressList.forEach((item, index) => {
            if (item.id == id) {
              item.default_set = 1;
              // item.splice(index, 1);
              this.addressList.splice(index, 1);
              this.addressList.unshift(item);
              console.log(item);
            } else {
              item.default_set = 0;
            }
          });
          this.userDefName = res.data.result.name;
          this.userDefAddress =
            res.data.result.area_name + res.data.result.desc;
          this.$message({
            type: "success",
            message: res.data.msg,
          });
          // let newRes = await getAddress({});
          // this.addressList = newRes.data.result;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  computed: {
    goodsNumber() {
      if (this.orderlist.length !== 0) {
        return this.orderlist.reduce((total, item) => {
          return (total += item.num);
        }, 0);
      } else {
        return 0;
      }
    },
    goodsSumPrice() {
      if (this.orderlist.length !== 0) {
        return this.orderlist.reduce((total, item) => {
          return (total += item.num * item.s_good.price);
        }, 0);
      } else {
        return 0;
      }
    },
    goodsDis() {
      if (this.orderlist.length !== 0) {
        return this.orderlist.reduce((total, item) => {
          return (total += item.s_good.sale_price * item.num);
        }, 0);
      } else {
        return 0;
      }
    },
    goodsPrice() {
      if (this.orderlist.length !== 0) {
        return this.orderlist.reduce((total, item) => {
          return (total +=
            item.num * (item.s_good.price - item.s_good.sale_price));
        }, 0);
      } else {
        return 0;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.shoppingAdress {
  background-color: rgb(247, 247, 247);
  .navTwo {
    height: 80px;
    position: relative;
  }

  main {
    margin: 0 auto;
    width: 100%;
    padding-bottom: 50px;
    background-color: rgb(255, 255, 255);

    .AddressBox {
      width: 100%;
      background-color: #fff;
      padding-top: 50px;
      .title {
        display: flex;
        justify-content: space-between;
        margin: 20px 0;
        .add {
          width: 150px;
          // border: 1px solid gray;
          background-color: red;
          border-radius: 5px;
          height: 50px;
          line-height: 50px;
          color: white;
          font-weight: bold;
          &:hover {
            cursor: pointer;
          }
        }
        .addresslength {
          height: 50px;
          width: 70%;
          background-color: #e3f2fd;
          // margin: 20px auto;
          text-align: left;
          line-height: 50px;
          padding-left: 20px;
          .el-icon-warning {
            color: skyblue;
            font-size: 15px;
          }
          p {
            font-size: 12px;
          }
        }
      }
    }

    .addBox {
      margin: 10px auto;
      border: 1px solid black;
      text-align: left;
      width: 900px;
      height: 350px;
      font-size: 25px;
      p {
        color: gray;
        margin: 15px;
        span {
          color: black;
        }
      }
      .ModifyAddress {
        display: flex;
        font-size: 15px;
        margin-left: 50%;
        p {
          color: white;
          border: 1px solid gray;
          background-color: black;
          border-radius: 15px;
          padding: 5px;
          width: 300px;
          line-height: 30px;
          text-align: center;
          transition: 0.5s;
          &:hover {
            cursor: pointer;
            color: black;
            background-color: white;
          }
        }
      }
    }
    .addAddressMask {
      background-color: rgba(0, 0, 0, 0.5);
      position: fixed;
      left: 0;
      top: 0;
      width: 100vw;
      // height: 80vh;
      // min-height: 1200px;
      z-index: 1000;
      .addressContent {
        width: 50%;
        // min-width: 800px;
        background-color: #fff;

        min-height: 600px;
        margin: 40px auto;
        .title {
          height: 80px;
          line-height: 80px;
          position: relative;
          h3 {
            font-weight: normal;
            font-size: 20px;
            text-align: center;
            border-bottom: 1px solid #eee;
            border-top: 6px solid #b12423;
          }
          i {
            position: absolute;
            right: 20px;
            top: 32px;
            font-size: 26px;
          }
        }
        .contentInput {
          box-sizing: border-box;
          padding: 0% 25%;
          > div {
            margin: 20px 0;
          }
          .xingbie {
            span {
              margin-right: 20px;
            }
            label {
              margin-right: 30px;
            }
            input {
              margin-right: 4px;
            }
          }
          .el-cascader {
            width: 100%;
          }
          #dizhi {
            margin-right: 10px;
            width: 16px;
            height: 16px;
          }
          .dizhi {
            padding-top: 30px;
            label {
              display: flex;
              align-items: center;
              input {
                display: block;
              }
              span {
                display: block;
              }
            }
          }
          p {
            span {
              text-decoration: underline;
              cursor: pointer;
            }
          }
          button {
            margin-top: 50px;
            width: 128px;
            height: 34px;
            background-color: #000;
            color: #fff;
            outline: none;
            border: 1px solid #000;
            transition: 0.5s;
            cursor: pointer;
          }
          button:hover {
            background-color: #fff;
            color: #000;
          }
        }
      }
    }
  }
  .table {
    width: 100%;
    // margin: 50px auto;
    border-color: gray;
    // border: 1px solid rgb(226, 224, 224);
    .updata {
      &:hover {
        color: red;
        cursor: pointer;
      }
    }
    .del {
      &:hover {
        color: red;
        cursor: pointer;
      }
    }
    .moren {
      &:hover {
        color: red;
        cursor: pointer;
      }
    }
    .Trheight {
      height: 50px;
      td {
        border: 1px solid rgb(226, 224, 224);
      }
      &:hover {
        background-color: rgb(211, 211, 211);
      }
      .default {
        border: 1px solid #ff5000;
        width: 70%;
        margin: 0 auto;
        line-height: 30px;
        border-radius: 5px;
        background-color: #ffd6cc;
        color: #f30;
      }
    }
    .THheight {
      height: 40px;
      background-color: rgb(242, 240, 240);
      font-weight: 300;
      th {
        font-weight: 300;
        font-size: 15px;
        border: 1px solid rgb(226, 224, 224);
      }
    }
  }
}
</style>
